package net.toocruel.iqismart.web.config;

import net.toocruel.iqismart.entity.setting.SettingEmail;
import net.toocruel.iqismart.service.SettingService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/8 上午1:20
 */
@Configuration
public class MailSender {
    @Autowired
    private SettingService settingService;
    @Bean
    public JavaMailSender javaMailSender(){
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        // 设定mail server
        SettingEmail email = settingService.getSetting().getEmail();
        senderImpl.setHost(email.getHost());
        senderImpl.setPort(email.getPort());
        senderImpl.setUsername(email.getUsername());                             // 根据自己的情况,设置发件邮箱地址
        senderImpl.setPassword(email.getPassword());                    // 根据自己的情况, 设置password
        senderImpl.setDefaultEncoding("UTF-8");
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true");                                 // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
        if(StringUtils.isBlank(email.getEncryption())){
            prop.put("mail.smtp.ssl.enable", "false");
        }else{
            prop.put("mail.smtp.ssl.enable", "true");
            if(email.getEncryption().equals("ssl")){
                prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            }else  if(email.getEncryption().equals("tls")){
                //TODO TLS
            }
        }

        senderImpl.setJavaMailProperties(prop);

        return senderImpl;
    }
}
